<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/24
 * Time: 14:17
 */

namespace app\storage\service;


use api\storage\common\Constant;
use app\storage\model\BomModel;
use app\storage\model\CarFileModel;
use app\storage\model\FileModel;
use service\file\CommonFile;
use think\Db;

class CarService extends CommonService
{
    public function addCar(){
        $data = $_POST;
        $kindFloor = [$data['aRow'], $data['bRow'], $data['cRow']];
        $kindCount = [$data['aCount'],$data['bCount'], $data['cCount']];
        $isDouble =  [$data['aisDouble'],$data['bisDouble'], $data['cisDouble']];

        Db::startTrans();
        $car = [
            'uuid' => create_uuid(),
            'car_id' => $data['carId'],
            'a_count' => $data['aCount'] * $data['aRow'],
            'b_count' => $data['bCount'] * $data['bRow'],
            'c_count' => $data['cCount'] * $data['cRow'],
            'status'=>0,
            'time' => get_current_time()
        ];
        $carSeat = [];
        $tranCarSeat = true;
        $tranCar = Db::table('iwh_car')->insert($car);
        for ($i = 0; $i <= 2; $i++) {
            $ascii = 65 + $i;
            for ($j = 1; $j <= $kindFloor[$i]; $j++) {
                if ($isDouble[$i] == 'yes') {
                    for ($k = 1; $k <= $kindCount[$i] / 2; $k++) {
                        $code = chr($ascii) . $j ."L" .  str_pad($k, 3, '0', STR_PAD_LEFT);
                        $temp = $this->CarSeatTemplate($car['uuid'],$code,chr($ascii));
                        array_push($carSeat, $temp);
                    }
                    for ($k = 1; $k <= $kindCount[$i] / 2; $k++) {
                        $code = chr($ascii) . $j."R" . str_pad($k, 3, '0', STR_PAD_LEFT);
                        $temp = $this->CarSeatTemplate($car['uuid'],$code,chr($ascii));
                        array_push($carSeat, $temp);
                    }
                } else {
                    for ($k = 1; $k <= $kindCount[$i]; $k++) {
                        $code = chr($ascii) .$j ."L". str_pad($k, 3, '0', STR_PAD_LEFT);
                        $temp = $this->CarSeatTemplate($car['uuid'],$code,chr($ascii));
                        array_push($carSeat, $temp);
                    }
                }
            }
        }

        if(!empty($carSeat)){
            $tranCarSeat = Db::table('iwh_car_seat')->insertAll($carSeat);
        }
        if($tranCarSeat !== false && $tranCar !== false ){
            Db::commit();
            ret_template(true,[],'新增成功');
        }else{
            Db::rollback();
            ret_template(false,[],'新增失败');
        }
    }

    private function CarSeatTemplate($carUuid,$code,$type){
        $carSeat = [
            'uuid' => create_uuid(),
            'car_uuid' => $carUuid,
            'seat_code' => $code,
            'seat_type' => $type,
            'status' => 0,
            'sub_materiel_id' => '',
            'reel_id' => '',
            'is_used' => 0,
            'time' => get_current_time()
        ];
        return $carSeat;
    }


    public function getCarListTitle($bomUuid)
    {
        $carFileModel = new CarFileModel();
        $carFile = $carFileModel->where('bom_uuid', $bomUuid)->value('file_path');
        $product = [];
        $bomId = [];
        if (!empty($carFile)) {
            $bomList = $carFileModel->where('file_path', $carFile)->column('bom_uuid');
            $bomModel = new BomModel();
            $bom = $bomModel->whereIn('uuid', $bomList)->field('order_id,fentryid,remark')->select();
            foreach ($bom as $item) {
                $start = strpos($item['remark'], ':');
                $productCode = substr(strstr($item['remark'], '数', true), $start + 1);
                $count = substr($item['remark'], strrpos($item['remark'], ':') + 1);
                $product[$productCode] = [
                    'productCode' => $productCode,
                    'count' => $product[$productCode]['count'] + $count
                ];
                $orderId = empty($item['fentryid']) ? $item['order_id'] : $item['order_id'] . '+' . $item['fentryid'];
                $bomId[] = $orderId . '(' . $count . ')';
            }
            foreach ($product as $k=>$item){
                $product[$k] = $item['productCode']. '(' . $item['count'] . ')';
            }
            $product = implode('、', $product);
            $bomId = implode('、', $bomId);
        }
        return [
            'bom' => empty($bomId) ? [] : $bomId,
            'product' => empty($product) ? [] : $product
        ];
    }


    public function getCarList($bomUuid)
    {
        $carSeat = []; //记录物料小车站位信息
        $bomReels = [];//记录装车Bom单的数量信息
        $materiel = []; //返回前端页面显示集合
        $count = -1;
        $finishedQty = [];
        $smtMateriel = [];
        $fileModel = new FileModel();
        $file = $fileModel->findFileByBomUuid($bomUuid);
        $storageUuid =$fileModel-> findStorageByBomUuid($bomUuid);
        if(empty($file)){
            return ret_template(false,'暂无装车文件');
        }
//        if (!file_exists($filePath)) {
//            return ret_template(false,'装车文件丢失');
//        }
        $file = new CommonFile($storageUuid,$file);
        $carReels = json_decode($file->read(), true);
        if (!empty($carReels)) {
            //存在合并Bom单装车情况下，将物料数量信息整合
            foreach ($carReels['bomIds'] as $order) {
                $outPutFile = new CommonFile($storageUuid, Constant::RECORD_OUTPUT_COUNT . $order . Constant::RECORD_FILE_SUFFIX);
                $bomContent = json_decode($outPutFile->read(), true);
                foreach ($bomContent as $k => $sub_materiel_id) {
                    if (!empty($bomReels[$k])) {
                        $bomReels[$k]['originalCount'] += $sub_materiel_id['originalCount'];
                        $bomReels[$k]['oughtCount'] += $sub_materiel_id['oughtCount'];
                    } else {
                        $bomReels[$k] = $sub_materiel_id;
                    }
                }
            }

            $materielId = array_column($carReels['data'], 'materielId');
            //处理小车清单站位显示，将有上车物料站位取出处理。
            //一单多次装车时存在一料一车一簇，一料一车多簇，一料多车多簇
            foreach ($carReels['data'] as $value) {
                $count += 1;
                $key = $value['materielId'];
                $carSeat[$key]['plateNumber'] += 1;
                $index = array_search($value['carId'], $carSeat[$key]['carId']);
                if ($index === false || $index === null) {
                    empty($carSeat[$key]['carId']) ? $carSeat[$key]['carId'] = [] : '';
                    array_push($carSeat[$key]['carId'], $value['carId']);
                    $carSeat[$key]['seatCode'][count($carSeat[$key]['carId']) - 1][0] = $value['seatCode'];
                } else {
                    //如果前后物料相同代表同一种物料连续存放用-连接
                    if ($materielId[$count - 1] == $materielId[$count] && $count != 0) {
                        $k = count($carSeat[$key]['seatCode'][$index]);
                        if ($k == 0 || substr($value['seatCode'], 0, 1) == 'C') {
                            $carSeat[$key]['seatCode'][$index][$k - 1] = $value['seatCode'];
                        } else {
                            if (empty($carSeat[$key]['seatCode'][$index][$k - 1])) {
                                $carSeat[$key]['seatCode'][$index] = [];
                            } else {
                                array_push($carSeat[$key]['seatCode'][$index], $value['seatCode']);
                            }
                        }
                    } else {
                        array_push($carSeat[$key]['seatCode'][$index], $value['seatCode']);
                    }
                }
            }

            //对物料的小车站位多维数组转一维数组 同一个物料同车不连续站位用、隔开，不同车通过/隔开
            $temp = [];
            foreach ($carSeat as $k => $value) {
                $temp[$k]['carId'] = implode('/', $value['carId']);
                foreach ($value['seatCode'] as $length => $item) {
                    $item = array_unique(array_filter($item));
                    if (is_array($item) && count($item) > 1) {
                        $item = min($item) . '-' . max($item);
                    } else {
                        $item = $item[0];
                    }
                    $temp[$k]['seatCode'] .= $item;
                    if ($length < count($value['seatCode']) - 1) {
                        $temp[$k]['seatCode'] .= '/';
                    }
                }
            }

            //处理小车清单各类数量信息显示及其备注
            $finishedQty = array_unique($finishedQty);

            foreach ($bomReels as $k => $value) {
                $materiel[$k]['sub_materiel_id'] = $k;
                $materiel[$k]['originalCount'] = $value['originalCount'];
                $materiel[$k]['measure'][0] = 0;
                foreach ($finishedQty as $key => $item) {
                    $materiel[$k]['measure'][$key] = sprintf("%d", $value['originalCount'] / $item);
                }
                $materiel[$k]['measure'] = implode('、', $materiel[$k]['measure']);
                $materiel[$k]['oughtCount'] = $value['oughtCount'];
                $materiel[$k]['secondCount'] = empty($secondContent[$k]['oughtCount']) ? '' : $secondContent[$k]['oughtCount'];
                $materiel[$k]['plateNumber'] = empty($carSeat[$k]['plateNumber']) ? 0 : $carSeat[$k]['plateNumber'];
                $materiel[$k]['carCode'] = empty($temp[$k]['carId']) ? '' : $temp[$k]['carId'];
                $materiel[$k]['seatCode'] = empty($temp[$k]['seatCode']) ? '' : $temp[$k]['seatCode'];
                if ($value['originalCount'] > $value['oughtCount']) {
                    $smtMateriel[$k] = [
                        'sub_materiel_id' => $k,
                        'count' => $materiel[$k]['originalCount'] - $materiel[$k]['oughtCount']
                    ];
                    $materiel[$k]['remark'] = "应补发({$smtMateriel[$k]['count']})";
                } else if ($value['originalCount'] == 0 && $value['planCount'] == 0 && $value['oughtCount'] == 0) {
                    $materiel[$k]['remark'] = '有替代';
                } else if ($value['originalCount'] != 0 && $value['planCount'] != 0 && $value['planCount'] > $value['oughtCount']) {
                    $materiel[$k]['remark'] = '欠料';
                } else {
                    $materiel[$k]['remark'] = '';
                }
            }
            $materiel = array_values($materiel);
            array_multisort(array_column($materiel, 'sub_materiel_id'), SORT_ASC, $materiel);
            return $materiel;
        }
        return [];
    }


}